//
//  CallingViewController.m
//  AipuTel
//
//  Created by cretve on 15/1/15.
//  Copyright (c) 2015年 aipu. All rights reserved.
//

#import "CallingViewController.h"
#import "AppDelegate.h"

@interface CallingViewController ()

@property (strong, nonatomic) AFHTTPRequestOperationManager *requestManager;

@property (weak, nonatomic) IBOutlet UILabel *titleLabel;

@end

@implementation CallingViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    AppDelegate* appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
    NSString* string = [appDelegate contactNameWithNumder:_number];
    if(string.length > 0)
        _titleLabel.text = [NSString stringWithFormat:@"  正在拨打：%@", string];
    else
        _titleLabel.text = [NSString stringWithFormat:@"  正在拨打：%@", _number];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleAppDidBecomeActive) name:UIApplicationDidBecomeActiveNotification object:nil];
    
    NSDictionary* userInfo = [[NSUserDefaults standardUserDefaults] dictionaryForKey:@"UsreInfo"];
    __weak CallingViewController* weakSelf = self;
    self.requestManager = [AFHTTPRequestOperationManager manager];
    [self.requestManager POST:@"http://202.98.133.196/ddserver/callback" parameters:@{@"caller": userInfo[@"username"], @"callee": _number} success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [weakSelf dismissViewControllerAnimated:YES completion:^{
            [UIAlertView bk_showAlertViewWithTitle:@"拨打失败，请稍候再试" message:nil cancelButtonTitle:@"好" otherButtonTitles:nil handler:nil];
        }];
    }];
}

- (void)handleAppDidBecomeActive
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (IBAction)clickedHangup:(UIButton *)sender
{
    [self.requestManager.operationQueue cancelAllOperations];
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

@end
